JavaScript中'&&'和'||'的返回值

今天看见一个题目

1
alert(1&&2)

初始觉得结果可能是true吧,任务逻辑运算符的返回值都是 truefalse ,但结果是 2

2 这个结果并不是很明白,翻了下 ECMA spec
>

  1. Let lref be the result of evaluating LogicalANDExpression.
  2. Let lval be GetValue(lref).
  3. Let lbool be ToBoolean(lval).
  4. ReturnIfAbrupt(lbool).
  5. If lbool is false, return lval.
  6. Let rref be the result of evaluating BitwiseORExpression.
  7. Return GetValue(rref).

第一个表达式值的bool值为false,则返回第一个表达式的值。否则返回第二个表达式的值。

因此可以发现下面几种结果很好理解了。

1
2
3
alert(false && 2) // false
alert(0 && 2) // 0
alert(1 && function(){}) // function(){}

||同理